import { RequestHandler } from 'express'
import { BadRequest } from 'http-errors'
import { failure, success } from '@/utils/response'
import { client, singleFileUpload } from '@/utils/aliyun'
import attachmentService from '@/services/attachmentService'

const uploadAliyun: RequestHandler = async (req, res) => {
  try {
    singleFileUpload(req, res, async function (error) {
      if (error) {
        return failure(res, error)
      }
      if (!req.file) {
        return failure(res, new BadRequest('请选择要上传的文件。'))
      }
      await attachmentService.createAttachment(req.userId as number, req.file)
      success(res, '上传成功。', { file: req.file.url })
    })
  } catch (error) {
    failure(res, error as Error, '上传失败：')
  }
}

export default {
  uploadAliyun,
}
